let ventEditor,selectProvinceName = '',selectCityCode = '',selectCityName = '',
	selectOccupationId = '',selectOccupationName = '',
//添加所有省份信息
allProvince = '110000,北京;120000,天津;130000,河北;140000,山西;150000,内蒙古;210000,辽宁;220000,吉林;230000,黑龙江;310000,上海;320000,江苏;330000,浙江;340000,安徽;350000,福建;360000,江西;370000,山东;410000,河南;420000,湖北;430000,湖南;440000,广东;450000,广西;460000,海南;500000,重庆;510000,四川;520000,贵州;530000,云南;540000,西藏;610000,陕西;620000,甘肃;630000,青海;640000,宁夏;650000,新疆;710000,台湾;810000,香港;820000,澳门',
provinceArray = allProvince.split(';'), provinceSpan = '';
for (let g = 0; g < provinceArray.length; g ++) {
	let pCodeName = provinceArray[g].split(',');
	provinceSpan += '<span class="province-obj choose-obj" id="' + pCodeName[0] + '">' + pCodeName[1] + '</span>';
}
$(function() {
	queryAllOccupation();
	initWangEditor();
	setMyHeader();
	$('.province-list div').append(provinceSpan);
    //点击页面
    $(document).click(function () {
        $('.hide-info,.vent-history').hide();
    });
    $('.choose-container').click(function (e) {
        $(this).find('.choose-list').show();
        e.stopPropagation();
    });
	$('.province-obj').click(function (e) {
		$(".province-list").hide();
		$('#showProvince').text(this.innerText);
		selectProvinceName = this.innerText;
		$('#showCity').text('城市');
		e.stopPropagation();
		let cityList = listCityByProvince(this.id);
		let cityListLen = cityList.length, cityArr = [];
		for (let g = 0; g < cityListLen; g ++){
			let cityObj = cityList[g];
			cityArr.push('<span class="choose-obj city-obj" id="' + cityObj.cityCode + '">' + cityObj.cityName + '</span>');
		}
		$('#listCity').empty().append(cityArr.join(''));
		$('.city-obj').click(function (e) {
			selectCityCode = this.id;
			selectCityName = this.innerHTML;
			$(this).parent().parent().hide();
			$('#showCity').text($(this).text());
			$('.city-list').hide();
			e.stopPropagation();
		});
	});

    $('.job-obj').click(function (e) {
        $(this).parent().parent().hide();
        $('#showJob').text(this.innerText);
        e.stopPropagation();
    });

    //点击其它地方则隐藏所有的选择下拉框
    $(document).one("click", function () {
        $(".choose-list,.vent-history").hide();
    });
	//发布吐槽
	$('#btnSubmitVent').click(function() {
		issueVent(this);
	});
	$('.login').click(function () {
		let ventObj = {
            title: V('ventName'),
            cityCode: selectCityCode,
            cityName: selectCityName,
            provinceName: selectProvinceName,
            occupationId: selectOccupationId,
            occupationName: selectOccupationName,
            ventTo: V('ventTo'),
            content: ventEditor.txt.html(),
            isAnonymous: $('#anonymousVent').is(':checked') ? 1 : 0,
            status: $('#vStatus').is(':checked') ? 1 : 0
        };
        sessionStorage.setItem('ventObj',JSON.stringify(ventObj));
		sessionStorage.setItem('backUrl','issueVent');
		location.href = 'ventLogin.html';
	});
	setVentFromLast();
    $('.myself-header').mouseover(function () {
        $('.myself-menu').show();
    });
    //页面加载完后过600毫秒才能获取到$('.myself-header').offset().left值
    setTimeout(function () {
        $('.myself-menu').css('left', ($('.myself-header').offset().left - 90) + 'px');
    },600);
	//搜索吐槽对象
	$('#ventTo,#ventName').keyup(function () {
		let thisInput = this, searchKey = this.value;
		if (isNull(searchKey)) {
			$('.vent-history').hide();
			return;
		}
		window.setTimeout(function () {
			if (searchKey == V(thisInput.id)) {
				listVentToName(thisInput,searchKey);
			}
		}, 500);
	});
});

/**
 * 从上一次的吐槽信息中重新设置吐槽表单，如从本页面跳到登录后再返回，重新赋值表单
 */
function setVentFromLast() {
	let ventStr = sessionStorage.getItem('ventObj');
	if (isNull(ventStr)){
	    return;
    }
	let ventObj = JSON.parse(ventStr);
    $('#showProvince').text(ventObj.provinceName);
    selectCityCode = ventObj.cityCode;
    $('#showCity').text(ventObj.cityName);
    selectOccupationId = ventObj.occupationId;
    $('#showJob').text(ventObj.occupationName);
    $('#ventTo').val(ventObj.ventTo);
    $('#ventName').val(ventObj.title);
    ventEditor.txt.html(ventObj.content);
    $('#anonymousVent').attr('checked',ventObj.isAnonymous == 1);
    $('#vStatus').attr('checked',ventObj.status == 1);
    sessionStorage.removeItem('ventObj');
}
/**
 * 查询所有职业类型
 */
function queryAllOccupation() {
	let occupationArray = getDictionaries('52');
	if (isNull(occupationArray)) {
		return;
	}
	let stOptionArr = [];
	//添加服务类型列表
	for (let j = 0; j < occupationArray.length; j ++) {
		let o = occupationArray[j];
		stOptionArr.push('<span class="choose-obj job-obj" id="' + o.id + '">' + o.dicName + '</span>');
	}
	$('#occupationList').append(stOptionArr.join(''));
	$('.job-obj').click(function () {
		selectOccupationId = this.id;
		selectOccupationName = this.innerText;
	});
}

//发布服务
function issueVent(btnSubmitVent) {
	if (!checkVentForm()) {
		return;
	}
	let ventHtml = ventEditor.txt.html(), imgHtml = getImgFromStr(ventHtml),
		ventText = ventEditor.txt.text();
	ventText = ventText.substring(0,180);
	setButtonStatus(btnSubmitVent,true,'吐槽中...');
	$.ajax({
		type: 'post',
		url : '/vent/saveVent',
		dataType: 'json',
		timeout: 120000,
		data: {
            'cityCode': selectCityCode,
            'occupationId': selectOccupationId,
            'ventTo': V('ventTo'),
            'title': V('ventName'),
            'content': filterXSS(ventHtml),
			'shortContent': ventText + '</div>' + imgHtml,
            'isAnonymous': $('#anonymousVent').is(':checked') ? 1 : 0,
			'status': $('#vStatus').is(':checked') ? 1 : 0
		},
		success: function(r) {
			if(r == 1){
				setErrorMsg('吐槽成功，再吐槽一个呗！');
				$('#ventTo,#ventName').val('');
				ventEditor.txt.text('');
			}else if (r == -2) {
				setErrorMsg('未获取到吐槽参数，请刷新页面再试');
			}else if(r.status == -1){
				setErrorMsg("未登录，请您登录后再吐槽");
			}else {
				setErrorMsg("抱歉，系统繁忙，请稍候再试");
			}
			setButtonStatus(btnSubmitVent,false,'吐槽');
		},
		error: function () {
			setErrorMsg("抱歉，系统开小差了，请稍候再试");
			setButtonStatus(btnSubmitVent,false,'吐槽');
		}
	});
}

function setErrorMsg(errorStr) {
	$('#errorMsg').text(errorStr);
}
/**
 * 检查表单必填项
 */
function checkVentForm() {
    if (isNull(selectCityCode)) {
        setErrorMsg('请选择城市');
        return false;
    }
    if (isNull(selectOccupationId)) {
        setErrorMsg('请选择职业');
        return false;
    }
    if (isNull(V('ventTo'))) {
		setErrorMsg('请填写要吐槽的对象/人/公司/行业');
		return false;
	}
	if (isNull(V('ventName'))) {
		setErrorMsg('请填写要吐槽的标题');
		return false;
	}
	let ventText = ventEditor.txt.text();
	if (isNull(ventText) || ventText.length < 8) {
		setErrorMsg('吐槽的内容不能小于8个字');
		return false;
	}
	setErrorMsg('');
	return true;
}

/**
 * 初始化编辑器
 */
function initWangEditor() {
    let date = new Date();
    let years = date.getFullYear(),month = date.getMonth() + 1;
    let imgPath = 'vent/' + years + month;
	ventEditor = new window.wangEditor('#ventContent');
	ventEditor.config.placeholder = '请输入要吐槽的正文，网络视频格式：&lt;iframe src="网络视频地址"&gt;&lt;/iframe&gt;';
	ventEditor.config.uploadImgServer = '/lglFile/uploadFile?imgPath=' + imgPath;
	ventEditor.config.uploadFileName = 'file';
	//图片不能超过3M
	ventEditor.config.uploadImgMaxSize = 3 * 1024 * 1024;
	ventEditor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
	//最多可传10张图片
	ventEditor.config.uploadImgMaxLength = 10;
	ventEditor.config.uploadImgHooks = {
		// 上传图片之前
		before: function(xhr) {
			// 可阻止图片上传
			/*return {prevent: true,msg: '需要提示给用户的错误信息'}*/
		},
		// 图片上传并返回了结果，图片插入已成功
		success: function(xhr) {
		},
		// 图片上传并返回了结果，但图片插入时出错了
		fail: function(xhr, editor, resData) {
			setErrorMsg('图片插入失败，请重试');
		},
		// 上传图片出错，一般为 http 请求的错误
		error: function(xhr, editor, resData) {
			setErrorMsg('图片上传出错，请重试');
		},
		// 上传图片超时
		timeout: function(xhr) {
			setErrorMsg('图片上传超时，请重试');
		},
		// 图片上传并返回了结果，想要自己把图片插入到编辑器中
		// 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
		customInsert: function(insertImgFn, result) {
			// result 即服务端返回的接口
			// insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
			insertImgFn('/apiImages/' + imgPath + '/' + result.fileName);
		}
	};
    /*ventEditor.config.uploadVideoServer = '/lglFile/uploadFile?imgPath=' + imgPath;
    ventEditor.config.uploadVideoMaxSize = 30 * 1024 * 1024; // 30m
    ventEditor.config.uploadVideoAccept = ['mp4'];*/
    ventEditor.create();
}

/**
 * 从字符串获取图片标签字符串
 * @param s 字符串来源
 * @returns {string} 图片标签字符串
 */
function getImgFromStr(s) {
	let imgArr = ['.jpg','.png','.jpeg','.gif','.bmp'], imgStr = '', imgIndex;
	for (let g = 0; g < imgArr.length; g ++){
		if (s.indexOf(imgArr[g]) > 0){
			imgStr = imgArr[g];
			imgIndex = s.indexOf(imgStr);
			break;
		}
	}
	if (isNull(imgStr)){
		return '';
	}
	let imgSubStr = s.substring(0,imgIndex);
	let beforeStrArr = imgSubStr.split('<');
	let imgHtml = '<' + beforeStrArr[beforeStrArr.length - 1];
	imgSubStr = s.substring(imgIndex,s.length - 1);
	imgSubStr = imgSubStr.substring(0,imgSubStr.indexOf('>'));
	if (imgHtml.indexOf(imgStr) < 0 && imgSubStr.indexOf(imgStr) < 0){
		imgHtml += imgStr;
	}
	return imgHtml + imgSubStr + '>';
}

/**
 * 获取吐槽对象或吐槽的内容
 * @param inputObj 输入框对象
 * @param ventToKey 搜索关键字
 */
function listVentToName(inputObj,ventKey) {
	if (isNull(ventKey)){
		return;
	}
	let ventToKey = '', ventNameKey = '';
	let inputId = $(inputObj).attr('id');
	if (inputId == 'ventTo'){
		ventToKey = ventKey;
	} else {
		ventNameKey = ventKey;
	}
	$.ajax({
		type: 'post',
		url : '/ventIndex/listVentToName',
		dataType: 'json',
		timeout: 120000,
		data: {ventToKey: ventToKey,ventNameKey: ventNameKey},
		success: function(ventList) {
			appendVentList(ventList,inputObj);
		}
	});
}

/**
 * 添加吐槽对象/吐槽内容数据集
 * @param ventList 数据集
 * @param inputId 输入框对象ID
 */
function appendVentList(ventList,inputObj) {
	if (isNull(ventList)){
		return;
	}
	let ventToArr = [];
	for (let g = 0; g < ventList.length; g ++){
		ventToArr.push('<div>' + ventList[g].ventTo + '</div>');
	}

	$('#' + $(inputObj).attr('showList')).empty().show().append(ventToArr.join('')).
	children('div').click(function () {
		let v = $(this).text();
		$(this).parent().hide().prev().val(v);
	});
}